var express         = require('express');
var path            = require('path');
var cookieParser    = require('cookie-parser');
var logger          = require('morgan');
var cors            = require('cors');

var database        = require('./utils/database');

var indexRouter     = require('./routes/index');
var setupRouter     = require('./routes/setup');
var authorityRouter = require('./routes/authority');
var roleRouter = require('./routes/role');
var  userRouter = require('./routes/users');

var app = express();

app.use(cors());
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use(async function(req, res, next) {
    var header  = req.header("Authorization");
    if (header) {
        var users   = await database.query(
            "SELECT `user`.* FROM `user_tokens` " + 
            "LEFT JOIN `user` ON(`user`.`id`=`user_tokens`.`user_id`) " + 
            "WHERE `user_tokens`.`token`=? AND `user_tokens`.`expire_at` > ?", 
            [header, new Date()]
        );
        req.user    = users.length === 1 ? users[0] : {};
    }
    next();
    // if (!header && req.path !== '/login') {
    //     res.status(401).json('Unauthorized');
    // }
});userRouter

app.use('/', indexRouter);
app.use('/setup', setupRouter);
app.use('/authority', authorityRouter);
app.use('/role',roleRouter);
app.use("/user",userRouter);

module.exports = app;
